const request = require('../../utils/https.js')
var util = require("../../utils/util.js");

import Page from '../../common/page';
import Notify from '../../dist/notify/notify';

var context = null;
var userId =null;
var fromUser, height;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        value: 1,
        isGetPhone: false,
        indicatorDots: false,
        vertical: false,
        autoplay: true,
        interval: 3000,
        duration: 1000,
        circular: true,
        typeClick: 0,
        total: 3,
        numbers: 1,
        minNum: 1,
        max:0,
        color: '',
        Index: 1,
        showWeal: false,
        fixed: 'relative',
        isHideToast: false,
        imagePath: '',
        isImg: false,
        houseIndex: 0,
        tips: false,
        rankName: 'VIP',
        goodsData: {
            has: true
        },
        has: true,
        loading: true,
        offline: false,
        height: 550,
        authorize: false,
        login: false,
        moveText: "",
        objWidth: 0,
        strWidth: 0,
        moveInfo: false,
        needTip: false,
        fontColor: "#7F7F7F",
        plData: {},
        prodName:"快美甄选",
        capsuleImg:""

    },
    // 监听滚动条滚动位置
    onPageScroll: function (e) { // 获取滚动条当前位置
        const that = this;
        if (e.scrollTop >= 690 / 2) {
            that.setData({
                fixed_status: true
            })

        } else {
            that.setData({
                fixed_status: false
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        //检查服务是否暂停
        request._get(getApp().Api_url + 'system', {}, function (res) {
            if (res.data.errMsg == 'OK') {
                var flag = res.data.data.on;
                if (!flag) {
                    wx.reLaunch({
                        url: '/pages/stop1/stop1'
                    })
                    return false;
                }
            }
        }, function () {
        })

        const that = this;
        userId = wx.getStorageSync('userId');
        let userInfo = wx.getStorageSync('userInfo'); //用户信息

        //判断是否是二维码进入的
        if (options.scene) {
            //获取到scene去兑换对应的 商品id 和 userId;

            request._get(getApp().Api_url + 'goods/byScene', {
                scene: options.scene
            }, function (res) {
                if (res.data.code == 200) {
                    let codeData = res.data.data;
                    wx.setStorageSync("fromUser", codeData.userId);
                    var goodsId = codeData.goodsId;
                    that.pullNoticeAll(goodsId);

                    that.getGoods(goodsId)
                    if (codeData.fast == 'true') {
                        var fast = true;
                    } else {
                        var fast = false;
                    }
                    that.setData({
                        show: false,
                        goodsId,
                        fast

                    })
                }
            }, function () {
            })
        } else {
            fromUser = options.userId; //上级userId
            if (fromUser != null  && fromUser !=undefined) {
                wx.setStorageSync("fromUser", fromUser);
            }
            var goodsId = options.goodsId;

            let channelId = options.channelId
            if (channelId != null && channelId != undefined && channelId != "") {
                wx.setStorageSync("channelId", channelId);
                let chUnionId = wx.getStorageSync('chUnionId');
                if (userId != null && userId != undefined && userId != "") {
                    request._get(getApp().Api_url + 'expand/spread_add', {
                        "channelId": channelId,
                        "chUnionId": chUnionId,
                        "prodId": goodsId,
                        "userId": userId,
                    }, function (ress) {

                    }, function () {
                    })
                } else {
                    let chUnionId = wx.getStorageSync('chUnionId');
                    if (chUnionId != null && chUnionId != undefined && chUnionId != "") {
                        request._get(getApp().Api_url + 'expand/spread', {
                            "channelId": channelId,
                            "chUnionId": chUnionId,
                            "prodId": goodsId,
                        }, function (ress) {

                        }, function () {
                        })
                    } else {
                        wx.login({
                            success(res) {
                                if (res.code) {
                                    request._get(getApp().Api_url + 'user/getOpenId', {
                                        "channelId": channelId,
                                        "jsCode": res.code
                                    }, function (ress) {
                                        if (ress.data.code == 200) {
                                            wx.setStorageSync("chUnionId", ress.data.unionId);
                                        }
                                    }, function () {
                                    })
                                }
                            }
                        })
                    }


                }
            }


            that.pullNoticeAll(goodsId);
            that.getGoods(goodsId)
            //判断是否是直升专区商品 有zone是专区商品

            if (options.fast == 'true') {
                var fast = true;
            } else {
                var fast = false;
            }
            //判断是否拉起购物车
            if (options.show == 0) {
                that.setData({
                    show: false,
                    goodsId,
                    fast
                })
            } else {
                that.setData({ //拉起购物车
                    show: true,
                    typeClick: 0,
                    goodsId,
                    fast
                })
                this.carDetail();
            }
        }


        if (userId) {
            //获取微信头像请求后台接口返回文件流 用于canvas 图片素材 用户头像

            if (userInfo.avatarUrl && userInfo.avatarUrl != '' && userInfo.avatarUrl != undefined && userInfo.avatarUrl != 'undefined' && userInfo.avatarUrl != null) {
                var avatarUrl = userInfo.avatarUrl
                wx.downloadFile({
                    url: getApp().Api_url + 'user/downloadIcon?pics=' + avatarUrl,
                    success(res) {
                        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                        if (res.statusCode == '200') {
                            wx.getImageInfo({
                                src: res.tempFilePath,
                                success: function (res) {
                                    that.data.iconUrl = res.path;
                                },
                                fail: function (res) {
                                    that.data.iconUrl = '';
                                }
                            })
                        }
                    }
                })
            } else {
                //更新用户信息
                wx.getUserInfo({
                    success: function (res) {
                        var avatarUrl = res.userInfo.avatarUrl
                        wx.downloadFile({
                            url: getApp().Api_url + 'user/downloadIcon?pics=' + avatarUrl,
                            success(res) {
                                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                                if (res.statusCode == 200) {
                                    wx.getImageInfo({
                                        src: res.tempFilePath,
                                        success: function (res) {
                                            that.data.iconUrl = res.path;
                                        },
                                        fail: function (res) {
                                            that.data.iconUrl = '';
                                        }
                                    })
                                }
                            }
                        })

                    }
                })
            }
        }
    },
    //商品详情
    getGoods(goodsId) {
        const that = this;
        request._get(getApp().Api_url + 'goods/listByGoodsId', {
            goodsId: goodsId,
            userId: userId
        }, function (res) {
            if (res.data.code == '200') {
                let goodsData = res.data.data;
                //用户是否有查看该商品权限
                if (goodsData.saw) {
                    that.setData({
                        goodsData: goodsData,
                        oneValue: goodsData.oneValue,
                        fast: goodsData.fast,
                        loading: false,
                        rankName: goodsData.rankName,
                        tradeNum: goodsData.stores.length < 1 ? '001' : goodsData.stores[0].tradeNum,
                        dynamicContent: goodsData.prodName, //绘标题文字,
                        prodName: goodsData.prodName, //绘标题文字,
                        height: goodsData.maxHeight,
                    })
                    that.getCode(goodsId)
                    //第一张图片设置高宽
                    let shareImg = goodsData.shareImg;
                    if( shareImg==null || shareImg == undefined || shareImg == "" ){
                        shareImg = goodsData.detailImg[0];
                    }
                    let capsuleImg = goodsData.capsuleImg;
                    if( capsuleImg==null || capsuleImg == undefined || capsuleImg == "" ){
                        capsuleImg = goodsData.carouselsImg[0];
                    }

                    that.setData({
                        capsuleImg:capsuleImg,
                        shareImg:shareImg,

                    })



                    wx.getImageInfo({
                        src: shareImg,
                        success: function (res) {
                            that.data.amongImg = res.path
                            var Width = res.width, //获取第一张图片真实宽度
                                Height = res.height,
                                ratio = Width / Height; //图片的真实宽高比例

                            var drawWidth = 540, //设置图片显示宽度
                                drawHeight = 540 / ratio; //计算的高度值

                            that.setData({
                                drawWidth: drawWidth, //第一张图的绘图宽度
                                drawHeight: drawHeight //第一张图的绘图高度
                            })
                        },
                        fail: function (res) {
                            that.data.amongImg = ''
                        }
                    })
                } else {
                    //没有查看权限跳转首页
                    wx.switchTab({
                        url: '/pages/list/list',
                    })
                }
            } else {
                //返回数据失败
                /* wx.reLaunch({
                  url: '/pages/login/login?goodsId=' + that.data.goodsId,
                }) */
            }
        }, function () {
            that.setData({
                loading: false,
                offline: true
            })
            wx.showToast({
                title: '网络不好，请稍后重试~~~',
                icon: 'none',
                duration: 2000
            })
        })
    },
    //获取小程序码图片并转码
    getCode(goodsId) {
        const that = this;
        if(userId!=null && userId != undefined && userId !=''){
            request._get(getApp().Api_url + 'goods/shareGoods?', {
                userId: userId,
                goodsId: goodsId,
                fast: that.data.fast

            }, function (res) {
                console.log('res.data.data==>', res.data.data)
                if (res.data.code == 200) {
                    console.log('res.data.code==>', res.data.code)
                    //获取网络图片本地路径生成canvas 图片素材 二维码
                    wx.getImageInfo({
                        src: res.data.data,
                        success: function (res) {
                            that.data.ewmUrl = res.path;
                        }
                    })
                } else {
                    that.setData({
                        ewmUrl: ''
                    })
                }
            }, function () {
            })
        }
    },
    //banner 数字切换
    onCurrent(e) {
        const that = this;
        that.setData({
            numbers: e.detail.current + 1
        })
    },
    //监听banner数量变化
    onChange(e) {
        const that = this;
        that.setData({
            value: e.detail
        })
    },
    onChange1(e) {
        wx.showToast({
            title: '直升商品限购 1 件!',
            icon: 'none',
            duration: 2000
        })
    },

    //拉起选择购物模态
    onkg(e) {
        const that = this;

        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?goodsId=' + that.data.goodsId,
            })
            return;
        }

        let typeClick = e.currentTarget.dataset.click; //控制购物车显示按钮 typeClick 0 拉起购物车,1 是 加入购物车

        if (that.data.goodsData.tips) { //判断是否是同级直升商品
            if (that.data.needTip) {
                let alterData = {
                    tips: true,
                    fixed: 'fixed',
                    rankName: that.data.goodsData.rankName,
                    typeClick: typeClick
                };

                that.setData({
                    noticeProd: true,
                    plData: alterData
                })

            } else {
                that.setData({
                    tips: true,
                    fixed: 'fixed',
                    rankName: that.data.goodsData.rankName,
                    typeClick: typeClick
                })
            }
            // that.setData({
            //     tips: true,
            //     fixed: 'fixed',
            //     rankName: that.data.goodsData.rankName,
            //     typeClick: typeClick
            // })
        } else {
            if (that.data.needTip) {
                let alterData = {
                    show: true,
                    typeClick: typeClick
                }
                that.setData({
                    noticeProd: true,
                    plData: alterData
                })
            } else {
                that.setData({
                    show: true, //显示模态
                    typeClick: typeClick
                })
            }
            // that.setData({
            //     show: true, //显示模态
            //     typeClick: typeClick
            // })

        }
        this.carDetail();


    },

    closeNoticeProd() {
        const that = this;
        let alterData = that.data.plData;
        console.log(alterData)
        alterData.noticeProd = false;
        console.log(alterData)
        that.setData(alterData)
    },


    //购物车数据
    carDetail() {
        const that = this;
        var io
        if (that.data.fast) { //专区商品
            io = 1
        } else {
            io = 0
        }

        request._get(getApp().Api_url + 'goods/detailByGoodsId', {
            userId: userId,
            goodsId: that.data.goodsId,
            io: io,
            tradeNum: that.data.tradeNum
        }, function (res) {
            if (res.data.code == 200) {
                let carData = res.data.data;
                //1.渲染出 每一项属性
                //2.选中默认的每一项选项
                //2.选中全部属性后才可以做加入购物车 和立即购买操作否则不能。

                if (carData.infos.length > 1) { //长度大于1
                    that.setData({
                        carData: carData,
                        imgUrl: carData.infos[0].childs[0].icons,
                        colorIndex: 0,
                        /* color,*/
                        imgId: carData.infos[0].childs[0].id,
                        sizeIndex: 0,
                        /* sizeText,*/
                        sizeId: carData.infos[1].childs[0].id
                    })
                    //根据每项属性 查价格
                    carData.kvMoney.forEach((v, i) => {

                        if (v.combineId == carData.infos[0].childs[0].id + ',' + carData.infos[1].childs[0].id || v.id == carData.infos[1].childs[0].id + ',' + carData.infos[0].childs[0].id) {

                            that.setData({
                                currentPrice: v.currentPrice,
                                rankPrice: v.rankPrice,
                                rankIcon: v.rankIcon,
                                prodPrice: v.prodPrice,
                                discountCate: v.discountCate,
                                sizeText: v.combineName,
                                skuId: v.id,
                                max: v.max,
                                buyNum: v.buyNum,
                                innerProds: v.innerProds,
                                innerTypes: v.innerTypes,
                                has: v.has,
                                fast: v.fast,
                                latest: v.latest,
                                number: v.number,
                                minNum: v.bottomNum,
                                value: v.bottomNum
                            })
                            if (v.number < v.bottomNum) {
                                that.setData({
                                    has: false
                                })
                            }
                        }
                    });
                } else {
                    that.setData({
                        carData: carData,
                        imgUrl: carData.infos[0].childs[0].icons,
                        colorIndex: 0,
                        /* color,*/
                        imgId: carData.infos[0].childs[0].id,
                    })
                    //根据每项属性 查价格
                    carData.kvMoney.forEach((v, i) => {

                        if (v.combineId == carData.infos[0].childs[0].id) {

                            that.setData({
                                currentPrice: v.currentPrice,
                                rankPrice: v.rankPrice,
                                rankIcon: v.rankIcon,
                                prodPrice: v.prodPrice,
                                discountCate: v.discountCate,
                                sizeText: v.combineName,
                                skuId: v.id,
                                max: v.max,
                                buyNum: v.buyNum,
                                innerProds: v.innerProds,
                                innerTypes: v.innerTypes,
                                has: v.has,
                                fast: v.fast,
                                latest: v.latest,
                                number: v.number,
                                minNum: v.bottomNum,
                                value: v.bottomNum
                            })
                            if (v.number < v.bottomNum) {
                                that.setData({
                                    has: false
                                })
                            }
                        }
                    });
                }

            }
        }, function () {
        })
    },
    //关闭模态
    onClose() {
        this.setData({
            show: false
        });
    },
    //复制手机号
    copyText: function (e) {
        wx.setClipboardData({
            data: e.currentTarget.dataset.text,
            success: function (res) {
                wx.getClipboardData({
                    success: function (res) {
                        wx.showToast({
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    },
    //提交订单
    goOrder(e) {
        const that = this;
        let user = wx.getStorageSync('user');
        request._get(getApp().Api_url + 'user/point', {
            userId: wx.getStorageSync("userId")
        }, function (res) {

            let pointNum = res.data.data; //总积分
            let value = that.data.value; //数量
            let points = that.data.goodsData.points; //商品价格积分

            if (res.data.success == true) {
                if (pointNum >= value * points) {
                    let goodsId = e.currentTarget.dataset.goodsid;
                    wx.navigateTo({
                        url: '/pages/order/order?goodsId=' + goodsId + '&value=' + value + '&pointNum=' + pointNum
                    })
                } else {
                    wx.showToast({
                        title: '您的KM还不够，赶快去赚取吧！',
                        icon: 'none',
                        duration: 2000
                    })
                }
            }
        }, function () {
        })
    },

    //点击图放大
    imgTapOne: function (e) {
        const that = this;
        let index = e.currentTarget.dataset.index;
        let bannerList = that.data.goodsData.carouselsImg;
        wx.previewImage({
            current: bannerList[index], // 当前显示图片的http链接
            urls: bannerList // 需要预览的图片http链接列表
        })
    },
    //点击图放大
    imgSlide: function (e) {
        const that = this;
        let index = e.currentTarget.dataset.index;
        let detailImg = that.data.goodsData.detailImg;
        wx.previewImage({
            current: detailImg[index], // 当前显示图片的http链接
            urls: detailImg // 需要预览的图片http链接列表
        })
    },

    //查看购物车商品颜色大图
    imgZoom() {
        const that = this;
        var colorList = that.data.carData.infos[0].childs;
        var imgZoomArr = [];
        if (that.data.colorIndex == '' || that.data.colorIndex == null || that.data.colorIndex == undefined) {
            imgZoomArr.push(colorList[0].icons);
        } else {
            imgZoomArr.push(colorList[that.data.colorIndex].icons);
        }

        wx.previewImage({
            current: imgZoomArr[0], // 当前显示图片的http链接
            urls: imgZoomArr // 需要预览的图片http链接列表
        })
    },
    //返回商城
    goShopping() {
        const that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //   url: '/pages/login/login?goodsId=' + that.data.goodsId,
            // })
            // return;
            userId = null;
        } else {
            wx.switchTab({
                url: '/pages/list/list'
            })
        }
    },
    //去购物车
    goCar() {
        const that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?goodsId=' + that.data.goodsId,
            })
            return;
        } else {
            wx.switchTab({
                url: '/pages/shopping_car/shopping_car'
            })
        }
    },
    //加入购物车
    addCar() {

        const that = this;
        //前端校验字段是否选择完全(颜色,尺寸,数量,商品Id)
        let temp = {
            skuId: that.data.skuId,
            count: that.data.value,
            userId: wx.getStorageSync("userId"),
            productId: that.data.goodsId,
            tradeNum: that.data.tradeNum

        }

        if (!this.checkData(temp)) {
            wx.showToast({
                title: '请选择颜色、尺码',
                icon: "none"
            })
            return false;
        }
        request._get(getApp().Api_url + 'cart/addToCart', temp, function (res) {
            if (res.data.errMsg == 'OK') {
                //添加购物车成功
                //根据接口返回是否添加成功 成功提醒
                that.setData({
                    num_icon: that.data.num_icon + that.data.value
                })
                Notify({
                    duration: 1000,
                    text: '加入购物车成功',
                    selector: '#custom-selector',
                    backgroundColor: '#F3544D',
                    safeAreaInsetTop: true
                });
                wx.showToast({
                    title: '成功加入购物车',
                    icon: 'success',
                    duration: 2000
                })

                that.onClose();

            }
        }, function () {
        })


    },
    //直接购买
    goBuy() {
        //前端校验字段是否选择完全(颜色,尺寸,数量,商品id)
        if (this.data.goodsData.tips) { //判断是否是同级直升商品
            this.setData({
                fixed: '',
                show: false
            })
            this.commonBuy1();
        } else {
            this.commonBuy();
        }

    },
    //确认提交
    onConfirm() {
        //
        if (this.data.typeClick == 1 || this.data.typeClick == 0) {
            this.addCar();
        }
        if (this.data.typeClick == 2) {
            this.commonBuy();
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //   url: '/pages/login/login?goodsId=' + that.data.goodsId,
            // })
            // return;
            userId = null;
        } else {
            that.setData({login: true})
        }
        this.goodsNum()
    },
    //购物车右上角icon
    goodsNum() {
        const that = this;
        //购物车数量
        request._get(getApp().Api_url + 'cart/goodsNum', {
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                that.setData({
                    num_icon: res.data.data
                })
            }
        }, function () {
        })
    },


    shareLogin() {
        const that = this;
        wx.reLaunch({
            url: '/pages/login/login?goodsId=' + that.data.goodsId,
        })
        return;
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        const that = this;
        let userId = wx.getStorageSync("userId");
        let goodsId = that.data.goodsId;
        let fast = that.data.fast;
        console.log("商品详情页点击了分享小程序按钮111112222")
        console.log("用户的id是:" + userId)

      /*  if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?goodsId=' + that.data.goodsId,
            })
            return;
        } else {*/
            if (res.from === 'button') {
                console.log("商品飞享页___",userId);
                console.log("商品详情页点击了分享小程序按钮2222")
                // 来自页面内转发按钮
                return {
                    title: that.data.prodName,
                    imageUrl: that.data.capsuleImg,
                    path: '/pages/gift_details/gift_details?userId=' + userId + '&goodsId=' + goodsId + '&show=0' + '&fast=' + fast
                }
            } else {
                console.log("商品飞享页___========",userId);
                console.log("商品详情页点击了分享小程序按钮333")
                return {
                    title: that.data.prodName,
                    imageUrl: that.data.capsuleImg,
                    path: '/pages/gift_details/gift_details?userId=' + userId + '&goodsId=' + goodsId + '&show=0' + '&fast=' + fast
                }
            }

      /*  }*/


    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    //检验手机号是否正确
    getPhoneNumber(e) {
        const that = this;
        util._getPhoneNumber(e, that)
    },
    //关闭获取手机号弹出
    onShut() {
        const that = this;
        that.setData({
            isGetPhone: false
        })
    },
    //立即购买(非直升商品)
    commonBuy() {

        //判断保税仓发货数量限制
        if (this.data.max > 0 && this.data.value > this.data.buyNum) {
            wx.showToast({
                title: `该商品限购,最多只能购买${this.data.buyNum}件!`,
                duration: 2000,
                icon: "none"
            })
            return false;
        }

        const temp = {
            fast: this.data.fast,
            prodName: this.data.goodsData.prodName,
            attributeNames: this.data.sizeText,
            prodPrice: this.data.prodPrice, //原价
            prodNum: this.data.value,
            prodImg: this.data.imgUrl,
            prodId: this.data.goodsData.prodId,
            currentPrice: this.data.currentPrice, //现价
            rankPrice: this.data.rankPrice, //会员价
            rankIcon: this.data.rankIcon,

            //discountCate: this.data.discountCate, //等于1 ,是直接定价 ：不等于1 ,是折扣率
            /* discountImg: this.data.goodsData.discountImg, */
            discountNum: this.data.goodsData.discountNum,
            inOrOut: this.data.goodsData.inOrOut,
            skuId: this.data.skuId,
            tradeNum: this.data.tradeNum,
            oneValue: this.data.oneValue //一口价 true是 false不是 */
        }
        if (!this.checkData(temp)) {
            wx.showToast({
                title: '请选择颜色、尺码',
                icon: "none"
            })
            return false;
        }
        let arr = [];
        let totalprice = temp.currentPrice * temp.prodNum;


        arr.push(temp);
        wx.setStorageSync("goods", JSON.stringify(arr));
        wx.setStorageSync("totalprice", totalprice);
        wx.navigateTo({
            url: '/pages/order1/order1?type=' + 2 + '&inOrOut=' + this.data.goodsData.inOrOut + '&link=gift' //立即支付
        })
    },
    //立即购买(直升商品)
    commonBuy1() {
        const temp = {
            fast: false,
            prodName: this.data.goodsData.prodName,
            attributeNames: this.data.sizeText,
            prodPrice: this.data.prodPrice, //原价
            prodNum: this.data.value,
            prodImg: this.data.imgUrl,
            prodId: this.data.goodsData.prodId,
            currentPrice: this.data.currentPrice, //现价
            rankPrice: this.data.rankPrice, //会员价
            rankIcon: this.data.rankIcon,

            //discountCate: this.data.discountCate, //等于1 ,是直接定价 ：不等于1 ,是折扣率
            /* discountImg: this.data.goodsData.discountImg, */
            discountNum: this.data.goodsData.discountNum,
            inOrOut: this.data.goodsData.inOrOut,
            skuId: this.data.skuId,
            tradeNum: this.data.tradeNum
        }
        if (!this.checkData(temp)) {
            wx.showToast({
                title: '请选择颜色、尺码',
                icon: "none"
            })
            return false;
        }
        let arr = [];
        let totalprice = temp.currentPrice * temp.prodNum;


        arr.push(temp);
        wx.setStorageSync("goods", JSON.stringify(arr));
        wx.setStorageSync("totalprice", totalprice);
        wx.navigateTo({
            url: '/pages/order1/order1?type=' + 2 + '&inOrOut=' + this.data.goodsData.inOrOut + '&link=gift' //立即支付
        })
    },

    //选择颜色函数
    onColor(e) {
        const that = this;
        let colorIndex = e.currentTarget.dataset.index;
        let imgId = e.currentTarget.dataset.imgid;
        let imgUrl = e.currentTarget.dataset.img;

        let carPriceArr = that.data.carData.kvMoney //购物车价格池子
        let color = e.currentTarget.dataset.color; //颜色名字


        that.setData({
            colorIndex: colorIndex,
            imgUrl: imgUrl,
            color,
            imgId,
            value: 1
        })

        if (that.data.carData.infos.length > 1) { //长度大于1
            //选择颜色查价格
            carPriceArr.forEach((v, i) => {
                if (v.combineId == that.data.sizeId + ',' + imgId || v.combineId == imgId + ',' + that.data.sizeId) {
                    that.setData({
                        currentPrice: v.currentPrice,
                        rankPrice: v.rankPrice,
                        rankIcon: v.rankIcon,
                        prodPrice: v.prodPrice,
                        discountCate: v.discountCate,
                        sizeText: v.combineName,
                        skuId: v.id,
                        max: v.max,
                        buyNum: v.buyNum,
                        innerProds: v.innerProds,
                        innerTypes: v.innerTypes,
                        has: v.has,
                        fast: v.fast,
                        number: v.number,
                        minNum: v.bottomNum,
                        value: v.bottomNum
                    })
                    if (v.number < v.bottomNum) {
                        that.setData({
                            has: false
                        })
                    }
                }
            });
        } else {
            //选择颜色查价格
            carPriceArr.forEach((v, i) => {
                if (v.combineId == imgId) {
                    that.setData({
                        currentPrice: v.currentPrice,
                        rankPrice: v.rankPrice,
                        rankIcon: v.rankIcon,
                        prodPrice: v.prodPrice,
                        discountCate: v.discountCate,
                        sizeText: v.combineName,
                        skuId: v.id,
                        max: v.max,
                        buyNum: v.buyNum,
                        innerProds: v.innerProds,
                        innerTypes: v.innerTypes,
                        has: v.has,
                        fast: v.fast,
                        number: v.number,
                        minNum: v.bottomNum,
                        value: v.bottomNum
                    })
                    if (v.number < v.bottomNum) {
                        that.setData({
                            has: false
                        })
                    }
                }

            });
        }


    },


    //选择尺寸函数
    onSize(e) {
        const that = this;
        let sizeIndex = e.currentTarget.dataset.index;
        let sizeId = e.currentTarget.dataset.sizeid;
        //let sizeText = e.currentTarget.dataset.text;
        let carPriceArr = that.data.carData.kvMoney //购物车价格池子

        that.setData({
            sizeIndex: sizeIndex,
            //sizeText,
            sizeId,
            value: 1
        })

        //选择尺寸查价格
        carPriceArr.forEach((v, i) => {

            if (v.combineId == sizeId + ',' + that.data.imgId || v.combineId == that.data.imgId + ',' + sizeId) {

                that.setData({
                    currentPrice: v.currentPrice,
                    rankPrice: v.rankPrice,
                    rankIcon: v.rankIcon,
                    prodPrice: v.prodPrice,
                    discountCate: v.discountCate,
                    sizeText: v.combineName,
                    skuId: v.id,
                    max: v.max,
                    buyNum: v.buyNum,
                    innerProds: v.innerProds,
                    innerTypes: v.innerTypes,
                    has: v.has,
                    fast: v.fast,
                    number: v.number,
                    minNum: v.bottomNum,
                    value: v.bottomNum
                })
            } else {

            }


        });

    },


    // 校验数据不为空
    checkData(data) {
        for (let key in data) {
            if (data[key] === '' || data[key] === undefined) {
                return false;
            }
        }
        return true;
    },
    //弹出转发朋友圈
    //用canvas绘制图片
    saveQRCode: function (e) {
        let that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?goodsId=' + that.data.goodsId,
            })
            return;
        }


        if (!that.data.ewmUrl) {
            wx.showToast({
                title: '小程序码未生成，请退出重试!',
                icon: 'none',
                duration: 2000
            })
            return;
        }

        if (!that.data.amongImg) {
            wx.showToast({
                title: '海报封面图未生成，请退出重试!',
                icon: 'none',
                duration: 2000
            })
            return;
        }

        if (!that.data.iconUrl) {
            wx.showToast({
                title: '用户头像未生成，请退出重试!',
                icon: 'none',
                duration: 2000
            })
            return;
        }

        wx.showLoading({
            title: '努力绘制中～',
        })

        // 设置画板显示，才能开始绘图
        context = wx.createCanvasContext('qrcode');
        context.setFillStyle("white")
        context.stroke();
        // 设置背景图
        var path = "../../images/white-bg.png"; //白色背景
        var logoUrl = that.data.ewmUrl; //二维码

        that.setData({ //画板高度
            canvasH: 180 + that.data.drawHeight
        })

        //var reg = /[\u4e00-\u9fa5]/g;
        //var names = that.data.dynamicContent.match(reg);
        //var textTie = 'aumo' + names.join(""); //商品名字描述


        //var arrLength = Math.ceil(textTie.length / 17);
        //处理发帖内容文字部分
        //var aa = '';
        //var j = 0; //记录行数
        //var k = 0;

        /* for (var i = 0; i < textTie.length; i++) {
          var enterStr = textTie.substring(i, i + 1);
          aa += enterStr;
          k++;
          console.log('enterStr==>', enterStr);
          if ((k % 17) == 0 || i == textTie.length || enterStr == "\n") {
            j++;
            var titleAa = util.toThousands(aa);
            aa = '';
            k = 0;
          }
        } */

        //画完帖子内容部分之后的高度
        //var drawHeightSucessHei = that.data.drawHeight + 240 + (40 * (j + 1));
        //画板总共的高度
        //var allHeight = (that.data.canvasH) + (40 * (j - 1));

        var allHeight = that.data.canvasH;

        context.drawImage(path, 0, 0, 540, allHeight); //白板背景

        context.drawImage(logoUrl, 50, that.data.drawHeight + 32, 130, 130) //二维码

        context.drawImage(that.data.amongImg, 0, 0, that.data.drawWidth, that.data.drawHeight); //(帖子图片详情图片)

        // 添加标题

        //var title1 = util.toThousands(' 我在 "快美帽饰aumo" 欣赏到一件');
        //var title2 = util.toThousands(' 时尚礼物，让我们一起拥有“她”');
        var title3 = util.toThousands('长按图片立即购买');
        var title4 = util.toThousands('邀请好友还可以获赠KM，抵扣现金');

        //绘制商品名字
        //that.drawWord();


        //绘制文字内容部分
        //1
        /*     context.setFontSize(24);
            context.setFillStyle("#333");
            context.fillText(title1, 120, 65);
            context.stroke(); */
        //2
        /*     context.setFontSize(24);
            context.setFillStyle("#333");
            context.fillText(title2, 120, 105);
            context.stroke(); */
        //3
        context.setFontSize(32);
        context.setFillStyle("#000");
        context.fillText(title3, 200, that.data.drawHeight + 95);
        context.stroke();
        //4
        context.setFontSize(16);
        context.setFillStyle("#ccc");
        context.fillText(title4, 205, that.data.drawHeight + 130);
        context.stroke();


        context.drawImage('../../images/ait.png', 80, 55, 150, 45)
        //context.drawImage('../../images/ait.png', 80, 46, 209, 63) //喜欢就买她png图片

        //截切头像圆形区域 sta
        context.beginPath(); //开始绘制
        //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
        context.arc(65, 75, 45, 0, Math.PI * 2, false);

        context.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因

        context.drawImage(that.data.iconUrl, 20, 30, 90, 90); //上角icon  logo,头像
        context.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
        //截切头像圆形区域 end

        //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        context.draw(true, setTimeout(function () {
            wx.canvasToTempFilePath({
                canvasId: 'qrcode',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    console.info(tempFilePath)
                    that.setData({
                        imagePath: tempFilePath
                    });
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success: function () {
                            console.log('同意授权=======>')
                            wx.saveImageToPhotosAlbum({
                                filePath: tempFilePath,
                                success: function (res) {
                                    setTimeout(function () {
                                        wx.hideLoading()
                                        that.setData({
                                            showWeal: false,
                                            fixed: 'fixed',
                                            isImg: true
                                        })
                                    }, 1200)
                                },
                                fail: function (res) {
                                    wx.hideLoading()
                                    that.setData({
                                        showWeal: false,
                                        fixed: '',

                                    })
                                }
                            })
                        },
                        fail: function (res) {
                            console.log('拒绝授权=======>')
                            wx.hideLoading()
                            that.setData({
                                showWeal: false,
                                fixed: 'fixed',
                                authorize: true
                            })
                            /* wx.showToast({
                              title: '您没有授权，无法保存到相册！',
                              icon: 'none',
                              duration: 2000
                            }); */
                        }
                    })

                },
                fail: function (res) {
                }
            });
        }, 500))

    },
    //绘制商品名字内容
    drawWord() {
        var that = this;
        var reg = /[\u4e00-\u9fa5]/g;
        var names = that.data.dynamicContent.match(reg);

        var textTie = 'aumo' + names.join(""); //商品名字描述
        var aa = '';
        var j = 0; //记录行数
        var k = 0;

        for (var i = 0; i <= textTie.length; i++) {

            var enterStr = textTie.substring(i, i + 1);
            aa += enterStr;
            k++;
            if ((k % 17) == 0 || i == textTie.length || enterStr == "\n") {
                j++;
                var titleAa = util.toThousands(aa);
                context.setFontSize(24);
                context.setFillStyle("#333");

                context.fillText(titleAa, 40, that.data.drawHeight + 220 + (40 * j));
                context.stroke();
                aa = '';
                k = 0;
            }

        }
    },
    // 分享朋友圈保存至相册
    gozf(e) {
        let that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?goodsId=' + that.data.goodsId,
            })
            return;
        }

        that.setData({
            showWeal: !that.data.showWeal,
            fixed: 'fixed'
        })
    },
    getPhoto() {
        const that = this;
        that.setData({
            isImg: false,
            fixed: ''
        })
        wx.showToast({
            title: '已保存到相册',
            icon: 'success',
            duration: 700
        })
    },
    // 关闭
    closezf() {
        let that = this;
        that.setData({
            showWeal: !that.data.showWeal,
            fixed: ''
        })
    },
    closeBig() {
        let that = this;
        that.setData({
            showWeal: false,
            fixed: ''
        })
    },
    //关闭好友公告打开分享
    shutToast() {
        const that = this;
        that.setData({
            isHideToast: false,
            tips: false,
            authorize: false,
            showWeal: !that.data.showWeal,
            fixed: ''
        })
    },

    //点击图片进行预览，长按保存分享图片
    previewImg: function (e) {
        var img = this.data.imagePath
        wx.previewImage({
            current: img, // 当前显示图片的http链接
            urls: [img] // 需要预览的图片http链接列表
        })
    },
    //选择仓库
    wareHouse(e) {
        const that = this;
        let houseIndex = e.currentTarget.dataset.index;
        let tradeNum = e.currentTarget.dataset.tradenum;
        that.setData({
            houseIndex: houseIndex,
            tradeNum: tradeNum
        })

    },
    //知道了跳转
    postOrder() {
        const that = this;
        that.setData({
            tips: false,
            show: true
        })
    },
    onAuthorize() {
        const that = this;
        that.setData({
            authorize: false
        })
    },
    colorRGB2Hex(color) {
        var rgb = color.split(',');
        var r = parseInt(rgb[0].split('(')[1]);
        var g = parseInt(rgb[1]);
        var b = parseInt(rgb[2].split(')')[0]);

        var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
        return hex;
    },
    pullNoticeAll(goodsId) {
        const that = this;
        request._get(getApp().Api_url + 'notice/pullTwo', {
            prodId: goodsId,
            type: "1"
        }, function (resData) {
            let resp = resData.data;
            console.log("拉取消息:" + goodsId + "---" + JSON.stringify(resp))
            if (resp.code == 200 && resp.data != null) {
                if (resp.data[0] != undefined) {
                    let res = resp.data[0];
                    if (res.strength == "0") {
                        let fontColor2 = that.colorRGB2Hex(res.fontColor);
                        that.setData({
                            moveText: res.content,
                            fontColor: fontColor2,
                            needTip: true
                        })
                    } else if (res.strength == "1") {
                        let info = wx.getSystemInfoSync();
                        let w = info.screenWidth;
                        let content = res.content;
                        let len = content.length * 15 + 4;
                        len = 0 - len;
                        if (res.fontColor != null && res.fontColor != "") {
                            if (res.bgImg != null && res.bgImg != "") {
                                that.setData({
                                    moveInfo: true,
                                    moveText: content,
                                    objWidth: w + "px",
                                    strWidth: len + "px",
                                    bgImg: "background:" + res.bgImg,
                                    fontColor: "color:" + res.fontColor,
                                    moveSelf: true
                                })
                            } else {
                                that.setData({
                                    moveInfo: true,
                                    moveText: content,
                                    objWidth: w + "px",
                                    strWidth: len + "px",

                                    fontColor: "color:" + res.fontColor,
                                    moveSelf: true
                                })
                            }
                        } else {
                            that.setData({
                                moveInfo: true,
                                moveText: content,
                                objWidth: w + "px",
                                strWidth: len + "px",
                                moveSelf: false
                            })
                        }
                    }
                }
            }
        }, function () {
        })
    }
})